package com.imoblife.brainwavestus.obpurchaseSystem;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.util.Log;
import com.imoblife.brainwavestus.tapjoy.TapjoyAwardPointsNotifier;
import com.imoblife.brainwavestus.tapjoy.TapjoyConnect;
import com.imoblife.brainwavestus.tapjoy.TapjoyConnectCore;
import com.imoblife.brainwavestus.tapjoy.TapjoyEarnedPointsNotifier;
import com.imoblife.brainwavestus.tapjoy.TapjoyLog;
import com.imoblife.brainwavestus.tapjoy.TapjoyNotifier;
import com.imoblife.brainwavestus.tapjoy.TapjoySpendPointsNotifier;
import com.imoblife.brainwavestus.tapjoy.VGStoreItem;
import com.imoblife.brainwavestus.users.HttpServerConnectionUtil;
import com.imoblife.brainwavestus.users.UserAccount;
import com.imoblife.brainwavestus.users.UsersUtil;
import com.imoblife.brainwavestus.util.DBUtil;
import com.imoblife.brainwavestus.util.DebugUtil;
import com.imoblife.brainwavestus.util.MakePurchaseStateChenge;


public class OBpurchaseSystem {
	static UserAccount user;
	static UsersUtil util;

	private static final String TAG = "OBpurchaseSystem";

	public interface OBPurchaseNotifier {

		public void noticeSuccess(String productId);

		public void noticeFailed(String errorInfo);
	}

	public interface OBNotifier {

		/**
		 * Callback containing the virtual currency name and total points
		 * information.
		 * 
		 * @param currencyName
		 *            The name of the virtual currency.
		 * @param pointTotal
		 *            Total number of virtual currency earned.
		 */
		public void getUpdatePoints(String currencyName, int pointTotal);

		/**
		 * Call containing error message if getTapPoints fails.
		 * 
		 * @param error
		 *            The error message for a failed request.
		 */
		public void getUpdatePointsFailed(String error);

	}

	public interface OBSpendPointsNotifier {
		/**
		 * Callback containing the virtual currency name and total points
		 * information.
		 * 
		 * @param currencyName
		 *            The name of the virtual currency.
		 * @param pointTotal
		 *            Total number of virtual currency earned.
		 */
		public void getSpendPointsResponse(String currencyName, int pointTotal);

		/**
		 * Call containing error message if spendTapPoints fails.
		 * 
		 * @param error
		 *            The error message for a failed request.
		 */
		public void getSpendPointsResponseFailed(String error);
	}

	public interface OBAwardPointsNotifier {
		/**
		 * Callback containing the virtual currency name and total points
		 * information.
		 * 
		 * @param currencyName
		 *            The name of the virtual currency.
		 * @param pointTotal
		 *            Total number of virtual currency earned.
		 */
		public void getAwardPointsResponse(String currencyName, int pointTotal);

		/**
		 * Call containing error message if spendTapPoints fails.
		 * 
		 * @param error
		 *            The error message for a failed request.
		 */
		public void getAwardPointsResponseFailed(String error);
	}

	public interface OBEarnedPointsNotifier {
		/**
		 * Callback whenever virtual currency has been earned. This can get
		 * called on a getTapPoints call.
		 * 
		 * @param amount
		 *            Amount of virtual currency earned (delta).
		 */
		public void earnedTapPoints(int amount);
	}

	public static String INTENT_ACT_UPDATE_POINTS = "intent_act_update_points";

	private static OBpurchaseSystem obpurchaseSystem;

	public void purchaseProduct(String productId,
			OBPurchaseNotifier purchaseNotifier, Context context) {
		
		DBUtil db = new DBUtil(mContext);
		
		String tapjoyId = db.openForRead()
				.getTapJoyIdByProductId(productId);
		db.closeDb();
		
		new BaseOnTJpurchaseSystem(context).purchaseVirtualGood(
				purchaseNotifier, tapjoyId);
	}

	public void getTapPoints(final OBNotifier notifier) {

		TapjoyConnect.getTapjoyConnectInstance().getTapPoints(
				new TapjoyNotifier() {

					public void getUpdatePointsFailed(String error) {
						notifier.getUpdatePointsFailed(error);
					}

					public void getUpdatePoints(String currencyName,
							int pointTotal) {

						notifier.getUpdatePoints(currencyName, pointTotal);
					}
				});
	}

	public void updateTapPoints() {
		TapjoyConnect.getTapjoyConnectInstance().getTapPoints(
				new TapjoyNotifier() {
					public void getUpdatePointsFailed(String error) {
						DebugUtil.debug(TAG, "update points>>" + error + "  "
								+ getPoints());
					}

					public void getUpdatePoints(String currencyName,
							int pointTotal) {
						Intent intent = new Intent(INTENT_ACT_UPDATE_POINTS);
						intent.putExtra("pointTotal", getPoints());
						mContext.sendBroadcast(intent);
						DebugUtil.debug(TAG, "update points>>" + pointTotal + "  "
								+ getPoints());
					}
				});
	}

	public void getTapPoints2() {
		TapjoyConnect.getTapjoyConnectInstance().getTapPoints(
				new TapjoyNotifier() {
					public void getUpdatePointsFailed(String error) {
					}

					public void getUpdatePoints(String currencyName,
							int pointTotal) {
						Log.d(TAG, "��⵽TAPJOY���Ϊ��" + pointTotal);
						TapjoyConnect.getTapjoyConnectInstance()
								.spendTapPoints(pointTotal,
										new TapjoySpendPointsNotifier() {

											public void getSpendPointsResponseFailed(
													String error) {
											}

											public void getSpendPointsResponse(
													String currencyName,
													int pointTotal) {
												Log.d(TAG, "����Ľ��ΪΪ��"
														+ pointTotal);
											}
										});
					}
				});
	}

	public void spendTapPoints(int amount, final OBSpendPointsNotifier notifier) {
		TapjoyConnect.getTapjoyConnectInstance().spendTapPoints(amount,
				new TapjoySpendPointsNotifier() {

					public void getSpendPointsResponseFailed(String error) {
						notifier.getSpendPointsResponseFailed(error);
					}

					public void getSpendPointsResponse(String currencyName,
							int pointTotal) {
						notifier.getSpendPointsResponse(currencyName,
								pointTotal);
					}
				});

	}

	public void awardTapPoints(int amount, final OBAwardPointsNotifier notifier) {
		TapjoyConnect.getTapjoyConnectInstance().awardTapPoints(amount,
				new TapjoyAwardPointsNotifier() {

					public void getAwardPointsResponseFailed(String error) {
						notifier.getAwardPointsResponseFailed(error);

					}

					public void getAwardPointsResponse(String currencyName,
							int pointTotal) {
						notifier.getAwardPointsResponse(currencyName,
								pointTotal);
						DebugUtil.debug(TAG, "���ͽ�ҡ��� pointTotal+" + pointTotal);
						Intent intent = new Intent(INTENT_ACT_UPDATE_POINTS);
						intent.putExtra("pointTotal", getPoint(pointTotal));
						mContext.sendBroadcast(intent);
					}
				});
	}

	public void setEarnedPointsNotifier(final OBEarnedPointsNotifier notifier) {
		TapjoyConnect.getTapjoyConnectInstance().setEarnedPointsNotifier(
				new TapjoyEarnedPointsNotifier() {

					public void earnedTapPoints(int amount) {

						notifier.earnedTapPoints(amount);
					}
				});
	}

	private static Context mContext;

	public static OBpurchaseSystem getOBpurchaseSystem(Context context) {
		user = new UserAccount(context.getApplicationContext());
		util = new UsersUtil(context.getApplicationContext());
		TapjoyConnect.requestTapjoyConnect(context.getApplicationContext(),
				"fc671786-cc67-4c1b-a48a-1b2c9aa1fd96", "3FyRgSovS4r87dQgpn6V");
		TapjoyLog.enableLogging(true);

		if (obpurchaseSystem == null) {
			obpurchaseSystem = new OBpurchaseSystem();
			mContext = context;
			if (!util.checkSupportGmail()) {
				obpurchaseSystem.updateTapPoints();
			}
		}

		return obpurchaseSystem;
	}

	public String getPoints() {
		StringBuffer buffer = new StringBuffer(
				TapjoyConnectCore.getLocalTapPointsTotal() + "");
		int size = buffer.length();
		for (int i = size - 3; i > 0; i -= 3) {
			buffer.insert(i, ", ");
		}
		return buffer.toString();
	}

	public int getTapjoyPoints() {
		return TapjoyConnectCore.getLocalTapPointsTotal();
	}

	public String getPoint(int points) {
		StringBuffer buffer = new StringBuffer(points + "");
		int size = buffer.length();
		for (int i = size - 3; i > 0; i -= 3) {
			buffer.insert(i, ",");
		}
		return buffer.toString();
	}

	public void showOffers() {
		TapjoyConnect.getTapjoyConnectInstance().showOffers();
	}

	public ArrayList<String> getPurchasedItems(Context service) {
		ArrayList<String> products = new ArrayList<String>();
		ArrayList<VGStoreItem> purchasedItems = new BaseOnTJpurchaseSystem(
				service).getAllPurchasedItemsFromServer();

		if (purchasedItems == null) {
			return null;
		}
		Log.v(TAG, "getPurchasedItems : " + purchasedItems.toString());

		for (VGStoreItem vgStoreItem : purchasedItems) {
//			String storeid = vgStoreItem.getVgStoreItemID();
//			DebugUtil.debug(TAG, storeid);
//			
//			Cursor cursor = SQLiteManager.getDatabaseInstence(mContext).query(
//					TJTable.TB_NAME, new String[] { TJTable.NAME },
//					TJTable.TBID + "=?", new String[] { storeid }, null, null,
//					null);
//			cursor.moveToFirst();
//			String productid = cursor.getString(0);
//			cursor.close();
//			
//			
//			products.add(productid);
		}

		return products;
	}

	private boolean isRestoreTransactions() {

		SharedPreferences sharedPreferences = mContext.getSharedPreferences(
				"TJTransactions", 1);

		return sharedPreferences.getBoolean("isRestore", true);
	}

	private void confirmRestoreTransacions() {
		SharedPreferences sharedPreferences = mContext.getSharedPreferences(
				"TJTransactions", 1);
		sharedPreferences.edit().putBoolean("isRestore", false).commit();
	}

	public void restoreTransactions(Context mActivity) {
		DebugUtil.debug(TAG, "restoreTransactions");

		DebugUtil.debug(TAG, "��Ҫ�ָ��˵�");
		ArrayList<String> products = getPurchasedItems(mActivity);

		if (products == null) {
			return;
		} else {
			for (String string : products) {
				
				MakePurchaseStateChenge.confirmProductState(mContext, string);
			}
		}
	}

	public String restoreTapjoyAndSendAllBill(Context context) {
		String result = null;
		ArrayList<String> products = getPurchasedItems(context);
		// StringBuilder urlParams = new StringBuilder();
		StringBuffer urlParams = new StringBuffer();
		String response = null;
		Log.v(TAG, "restoreTapjoyAndSendAllBill : " + products.toString());
		if (products == null) {
			result = "0";
		} else {
			// for (String string : products) {
			// DebugTool.debug(TAG, "�ظ��˵�>> " + string);
			// urlParams.append(string).append("|");
			// }
			for (int i = 0; i < products.size(); i++) {
				urlParams.append(products.get(i));
				urlParams.append("|");
			}
			try {
				// urlParams.deleteCharAt(products.size() - 1);
				Log.v(TAG, "restoreTapjoyAndSendAllBill >> �ָ����˵�" + urlParams);
				response = HttpSendAllMusicBill(urlParams.toString());
				Log.v(TAG, "restoreTapjoyAndSendAllBill >> response = "
						+ response);
				if (response.equals("1")) {
					result = "1";
				} else if (response.equals("0")) {
					result = "0";
				} else if (response.equals("unsuccess")) {
					result = "0";
				}
			} catch (Exception e) {
				e.printStackTrace();
				// String excep_response = HttpSendAllMusicBill("null");
				// Log.v(TAG, "restoreTapjoyAndSendAllBill >> excep_response = "
				// + excep_response);
				result = "nobilling";
			}
		}
		return result;
	}

	public boolean promptRestoreTransactions(Activity activity) {
		DebugUtil.debug(TAG, "restoreTransactions");

		synchronized (OBpurchaseSystem.class) {

			DebugUtil.debug(TAG, "��Ҫ�ָ��˵�");
			ArrayList<String> products = getPurchasedItems(activity);

			if (products == null) {
				DebugUtil.debug(TAG, "tj�ظ��˵�ʧ��");
				return false;
			} else {
				for (String string : products) {
					DebugUtil.debug(TAG, "�ظ��˵�>> " + string);
					MakePurchaseStateChenge.confirmProductState(mContext,
							string);
				}
			}

			return true;
		}

	}

	public boolean restoreTransaction(Activity activity) {

		ArrayList<String> products = getPurchasedItems(activity);
		DebugUtil.debug(TAG, products.toString());
		if (products == null) {
			
			return false;
		} else {
			for (String string : products) {
				
				MakePurchaseStateChenge.confirmProductState(activity, string);
			}
			confirmRestoreTransacions();
			return true;
		}

	}

	public String userRestoreTransactions(String lock) {
		
		String response = null;
		try {
			if (lock.equals("lock")) {
				response = HttpLoginGetAllMusicBill();
			} else {
				response = HttpGetAllMusicBill();
			}

			Log.v(TAG, "userRestoreTransactions >> response = " + response);
			if (response.equals("unsuccess") || response == null) {
				return "0";
			} else if (response.equals("1")) {
				return "1";
			} else {
				String[] bill = response.split("\\|");
				for (int i = 0; i < bill.length; i++) {
					MakePurchaseStateChenge.confirmProductState(mContext,
							bill[i]);
				}
				return "2";
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "0";
		}

	}

	public String userRestoreTransactions2(String lock) {
		DebugUtil.debug(TAG, "��Ҫ�ָ��˵�");
		String response = null;
		try {
			if (lock.equals("lock")) {
				response = HttpLoginGetAllMusicBill();
			} else {
				response = HttpGetAllMusicBill();
			}

			Log.v(TAG, "userRestoreTransactions2 >> response = " + response);
			if (response.equals("unsuccess") || response == null) {
				return "0";
			} else if (response.equals("1")) {
				return "1";
			} else {
				String[] bill = response.split("\\|");
				for (int i = 0; i < bill.length; i++) {
					MakePurchaseStateChenge.confirmProductState2(mContext,
							bill[i]);
				}
				return "2";
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "0";
		}

	}

	/*
	 * public class getAllMusicBillAsyncTask extends AsyncTask<String, Void,
	 * String> {
	 * 
	 * 
	 * protected String doInBackground(String... params) { String result = "";
	 * try { HttpPost request = new
	 * HttpPost(HttpServerConnectionUtil.GETMUSICBILL_PATH);
	 * ArrayList<NameValuePair> list = new ArrayList<NameValuePair>();
	 * list.add(new BasicNameValuePair("gmail", params[0]));
	 * request.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
	 * HttpResponse response = new DefaultHttpClient().execute(request); if
	 * (response.getStatusLine().getStatusCode() == 200) { result =
	 * EntityUtils.toString(response.getEntity()); return result; }else{ result
	 * = "unsuccess"; } } catch (Exception e) { e.printStackTrace(); } return
	 * result; }
	 * 
	 * 
	 * protected void onPostExecute(final String result) {
	 * super.onPostExecute(result); if (result.equals("0")) {
	 * System.out.println("�û�û�й�����Ŀ"); }else if(result.equals("unsuccess")){
	 * Toast.makeText(mContext, "�������", 3000).show(); }else{ String[] allMusic
	 * = result.split("\\|"); for (int i = 0; i < allMusic.length; i++) {
	 * allMusicBill.add(allMusic[i]); } } } }
	 */

	public String HttpLoginGetAllMusicBill() {
		String urlPath = HttpServerConnectionUtil.GETMUSICBILL_PATH + "?gmail="
				+ user.getGmail() + "&lock=0";
		try {
			URL url = new URL(urlPath);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setConnectTimeout(10000);
			connection.setReadTimeout(10000);
			connection.connect();
			if (connection.getResponseCode() == 200) {
				BufferedReader br = new BufferedReader(new InputStreamReader(
						connection.getInputStream()));
				StringBuilder builder = new StringBuilder();
				String line = null;
				while ((line = br.readLine()) != null) {
					builder.append(line);
				}
				return builder.toString();
				// Log.v(TAG, "����ֵ��"+response);
			} else {
				return "unsuccess";
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public String HttpGetAllMusicBill() {
		String urlPath = HttpServerConnectionUtil.GETMUSICBILL_PATH + "?gmail="
				+ user.getGmail() + "&lock=1";
		try {
			URL url = new URL(urlPath);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setConnectTimeout(10000);
			connection.setReadTimeout(10000);
			connection.connect();
			if (connection.getResponseCode() == 200) {
				BufferedReader br = new BufferedReader(new InputStreamReader(
						connection.getInputStream()));
				StringBuilder builder = new StringBuilder();
				String line = null;
				while ((line = br.readLine()) != null) {
					builder.append(line);
				}
				return builder.toString();
				// Log.v(TAG, "����ֵ��"+response);
			} else {
				return "unsuccess";
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public String HttpSendAllMusicBill(String params) {
		Log.v(TAG, "HttpSendAllMusicBill >> music = " + params);
		String response = "";
		String urlPath = HttpServerConnectionUtil.SETMUISCBILL_PATH + "?gmail="
				+ user.getGmail() + "&music=" + params + "&update=1";
		try {
			URL url = new URL(urlPath);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setConnectTimeout(10000);
			connection.setReadTimeout(10000);
			connection.connect();
			if (connection.getResponseCode() == 200) {
				BufferedReader br = new BufferedReader(new InputStreamReader(
						connection.getInputStream()));
				StringBuilder builder = new StringBuilder();
				String line = null;
				while ((line = br.readLine()) != null) {
					builder.append(line);
				}
				response = builder.toString();
			} else {
				response = "unsuccess";
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return response;
	}
}
